<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
                        v-model="queryParams.orderTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="顾客信息" prop="orderConsumerId">
        <el-input
          v-model="queryParams.orderConsumerId"
          placeholder="请输入顾客信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品信息" prop="orderCommodityId">
        <el-input
          v-model="queryParams.orderCommodityId"
          placeholder="请输入商品信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单金额" prop="orderSummer">
        <el-input
          v-model="queryParams.orderSummer"
          placeholder="请输入订单金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款方式" prop="orderStyle">
        <el-input
          v-model="queryParams.orderStyle"
          placeholder="请输入付款方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配送地址" prop="orderSent">
        <el-input
          v-model="queryParams.orderSent"
          placeholder="请输入配送地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="orderOthers">
        <el-input
          v-model="queryParams.orderOthers"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="id"/>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="顾客信息" align="center" prop="orderConsumerId">
        <template slot-scope="scope">
          <div>
          {{ConsumerById(scope.row.orderConsumerId)}}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="商品信息" align="center" prop="orderCommodityId">
        <template slot-scope="scope">
          <div>
            {{CommodityById(scope.row.orderCommodityId)}}
<!--            {{scope.row.orderCommodityId.forEach(myId=>{CommodityById(myId)}) }}-->
          </div>
        </template>
      </el-table-column>

      <el-table-column label="订单金额" align="center" prop="orderSummer"/>
      <el-table-column label="付款方式" align="center" prop="orderStyle"/>
      <el-table-column label="配送地址" align="center" prop="orderSent"/>
      <el-table-column label="备注" align="center" prop="orderOthers"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单金额对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
                          v-model="form.orderTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="顾客信息" prop="orderConsumerId">
          <el-select v-model="form.orderConsumerId" @change="handleAddress">
            <el-option
              v-for="consumer in this.$data.customerList"
              :key="consumer.id"
              :label="consumer.consumerName"
              :value="consumer.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品信息" prop="orderCommodityId">
          <el-checkbox-group v-model="selectedCommodities" @change="handleTotal">
            <el-checkbox v-for="commodity in commodityList" :key="commodity.id" :label="commodity.id" :value="commodity.id">
              {{ commodity.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="订单金额" prop="orderSummer">
          <el-input v-model="form.orderSummer" placeholder="请输入订单金额"/>
        </el-form-item>
        <el-form-item label="付款方式" prop="orderStyle">
<!--          <el-input v-model="form.orderStyle" placeholder="请输入付款方式"/>-->
          <el-select v-model="form.orderStyle">
            <el-option
              v-for="payway in payWayList"
              :key="payway.name"
              :label="payway.name"
              :value="payway.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送地址" prop="orderSent">
          <el-input v-model="form.orderSent" placeholder="请输入配送地址"/>
        </el-form-item>
        <el-form-item label="备注" prop="orderOthers">
          <el-input v-model="form.orderOthers" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addOrder,
  delOrder,
  getOrder,
  listCommodity,
  listCommodityById,
  listConsumerById,
  listCustomer,
  listOrder,
  updateOrder
} from "@/api/system/order";

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单金额表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderTime: null,
        orderConsumerId: null,
        orderCommodityId: null,
        orderSummer: null,
        orderStyle: null,
        orderSent: null,
        orderOthers: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        orderTime: [
          {required: true, message: "下单时间不能为空", trigger: "blur"}
        ],
        orderConsumerId: [
          {required: true, message: "顾客信息不能为空", trigger: "blur"}
        ],
        orderCommodityId: [
          {required: true, message: "商品信息不能为空", trigger: "blur"}
        ],
        orderSummer: [
          {required: true, message: "订单金额不能为空", trigger: "blur"}
        ],
        orderStyle: [
          {required: true, message: "付款方式不能为空", trigger: "blur"}
        ],
      },
      //  客户信息回显数据
      customerList: [],
      commodityList: [],
      // 这是多选框的
      selectedCommodities: [],
      payWayList: [
        { id: 1, name: "微信" },
        { id: 2, name: "支付宝" },
        { id: 3, name: "其他" }
      ],
    };
  },
  created() {
    this.getList();

  },

  methods: {
    /** 查询订单金额列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.orderList.forEach(res=>{
          // 订单字符串转为数字数组
          let ids = res.orderCommodityId
          // console.log(ids.split(",").map(Number))
          res.orderCommodityId =ids.split(",").map(Number);
          // res.orderCommodityId =Number(res.orderCommodityId);
          // console.log(res.orderCommodityId.splice(','))
        });
        this.total = response.total;
        this.loading = false;
      });
      // 查询客户表
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
      });
      // 查询商品表
      listCommodity(this.queryParams).then(response => {
        this.commodityList = response.rows;
      });
      // listConsumerById(1).then(res => {
      //   pass
      // });
    },
    // 通过id 找到消费者
    ConsumerById(id) {
      const consumer = this.customerList.find(item => item.id === id)
      return consumer.consumerName
    },
    // 通过id找到商品
    CommodityById(ids) {
      let commodity = "";
      for (let i in ids){
        if(Number(i) === ids.length-1){
          commodity += this.commodityList.find(item => item.id === ids[i]).name
        }else {
          commodity += this.commodityList.find(item => item.id === ids[i]).name + "~"
        }
      }

      return commodity;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderTime: null,
        orderConsumerId: null,
        orderCommodityId: null,
        orderSummer: null,
        orderStyle: null,
        orderSent: null,
        orderOthers: null
      };
      this.resetForm("form");
      this.selectedCommodities = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    handleAddress(id) {

      listConsumerById(id).then(res => {
        this.form.orderSent = res.rows[0].consumerAddress;
      })
    },
    handleTotal() {
      let sum = 0
      for(let i in this.selectedCommodities){
        sum += this.commodityList.find(item => item.id === this.selectedCommodities[i]).price
      }
      this.form.orderSummer = sum;
      this.form.orderCommodityId = this.selectedCommodities

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        // console.log(this.form.orderCommodityId.split(",").map(Number))
        this.selectedCommodities = this.form.orderCommodityId.split(",").map(Number)
        this.open = true;
        this.title = "修改订单金额";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.orderCommodityId = this.form.orderCommodityId.toString();
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // console.log(this.form.orderCommodityId)
            this.form.orderCommodityId = this.form.orderCommodityId.toString();
            // console.log(this.form.orderCommodityId);
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单金额编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
